package io.huaguoguo.conf;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.XmlUtil;
import io.huaguoguo.connector.Connector;
import lombok.Getter;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.util.ArrayList;
import java.util.List;

/**
 * 描述： server.xml配置内容  <br>
 * CreateDate: 2021/11/25 <br>
 *
 * @author huaguoguo
 */
@Getter
public class ServerConf {
    private List<Connector> connectors;

    public ServerConf(String xmlPath) {
        load(xmlPath);
    }

    public ServerConf() {
        this("server.xml");
    }

    private void load(String xmlPath) {
        Document document = XmlUtil.readXML(xmlPath);
        connectors = loadConnectorConf(document);
    }

    private List<Connector> loadConnectorConf(Document document) {
        NodeList nodeList = XmlUtil.getNodeListByXPath("Server/Service/Connector", document);
        int length = nodeList.getLength();
        Assert.isTrue(length > 0,"没有找到Server/Service/Connector节点，请配置！");
        List<Connector> list = new ArrayList<>(length);
        for (int i = 0; i < length; i++) {
            Connector conf = new Connector();
            Node node = nodeList.item(i);
            conf.setPort(Integer.parseInt(node.getAttributes().getNamedItem("port").getNodeValue()));
            conf.setProtocol(node.getAttributes().getNamedItem("port").getNodeValue());
            conf.setConnectionTimeout(Integer.parseInt(node.getAttributes().getNamedItem("connectionTimeout").getNodeValue()));
            conf.setRedirectPort(Integer.parseInt(node.getAttributes().getNamedItem("redirectPort").getNodeValue()));
            list.add(conf);
        }
        return list;
    }
}
